package com.hinnotek.amoeba.ui.activity.old

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.activity.viewModels
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.gson.Gson
import com.lee.common.base.BaseActivity
import com.hinnotek.amoeba.R
import com.hinnotek.amoeba.adapters.old.ImageSelectGridAdapter
import com.hinnotek.amoeba.base.BaseBean
import com.hinnotek.amoeba.bean.old.AmeobaCustomerListBean
import com.hinnotek.amoeba.bean.old.AmibaProjectListBean
import com.hinnotek.amoeba.bean.old.AmibaReimburseProjectJson
import com.hinnotek.amoeba.bean.old.AmibaSysUserAdminBean
import com.hinnotek.amoeba.databinding.ActivityWipeOutAddBinding
import com.hinnotek.amoeba.databinding.IncludeWoWipeOutAddLayoutBinding
import com.hinnotek.amoeba.dialog.CustomDialog
import com.hinnotek.amoeba.ext.initAdapter
import com.hinnotek.amoeba.utilities.*
import com.hinnotek.amoeba.viewmodels.AmibaReimburseViewModel
import com.hinnotek.amoeba.viewmodels.PublicInterfaceViewModel
import com.lee.common.network.getRequestBody
import com.lee.common.network.net.ObserverState
import com.lee.common.utils.SharedPreUtils
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.entity.LocalMedia
import com.xuexiang.xutil.common.StringUtils
import java.io.File
import java.io.FileNotFoundException
import java.util.*

class WipeOutAddActivity : BaseActivity<ActivityWipeOutAddBinding>(),
    ImageSelectGridAdapter.OnAddPicClickListener {

    private var mSelectList: MutableList<LocalMedia> = mutableListOf()
    private var applyUserType = 0
    private var orgId = 0
    private var customerId = 0
    private var amibaCustomerProjectId = 0
    private var amibaProjectId = 0
    private var approvalUserId = 0
    private var orgName: String = ""

    private var mAdapter: ImageSelectGridAdapter? = null

    private val viewModel by viewModels<AmibaReimburseViewModel>()
    private val publicViewModel by viewModels<PublicInterfaceViewModel>()


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setLeftVisible(true)
        setTitle("添加报销申请")

        setContentView(R.layout.activity_wipe_out_add)
    }

    override fun initVew() {

        bindingView.rbWoP.setOnCheckedChangeListener { buttonView, isChecked ->
            if (isChecked) {
                bindingView.llChooseUnit.visibility = View.GONE
                bindingView.llWoChooseProject.visibility = View.GONE
                bindingView.llWoChoosePdProject.visibility = View.VISIBLE
            } else {
                bindingView.llChooseUnit.visibility = View.VISIBLE
                bindingView.llWoChooseProject.visibility = View.VISIBLE
                bindingView.llWoChoosePdProject.visibility = View.GONE
            }
        }
        bindingView.tvWoHappenDate.setOnClickListener {
            IntentUtils.startActivityForResult(
                this,
                MaterialDesignCalendarActivity::class.java,
                null,
                111
            )
        }
        bindingView.rbWoDetails.setOnClickListener {
            val productBinding = DataBindingUtil.inflate<IncludeWoWipeOutAddLayoutBinding>(layoutInflater,R.layout.include_wo_wipe_out_add_layout, bindingView.llWoDetails, false)
            bindingView.llWoDetails.addView(productBinding.root)
            productBinding.tvWoHappenDate.setOnClickListener {
                IntentUtils.startActivityForResult(
                    this@WipeOutAddActivity,
                    MaterialDesignCalendarActivity::class.java,
                    null,
                    222
                )
            }
            productBinding.tvDel
                .setOnClickListener { v1: View? -> bindingView.llWoDetails.removeView(productBinding.root) }
        }
        bindingView.superButtonSubmit.setOnClickListener(View.OnClickListener { v: View? ->
            if (ClickUtil.isFastClick()) {
                return@OnClickListener
            }
            val amibaReimburseProjectJson = mutableListOf<AmibaReimburseProjectJson>()
            var provideProjectName=""
            var customerName=""
            var projectName=""
            if (bindingView.rbWoP.isChecked) {
                provideProjectName = bindingView.escWoChoosePdProject.editText.text.toString().trim()
                if (StringUtils.isEmpty(provideProjectName)) {
                    ToastUtils.show(mContext, "请选择选择项目")
                    return@OnClickListener
                }
            } else {
                customerName = bindingView.escWoChooseUnit.editText.text.toString().trim()
                if (StringUtils.isEmpty(customerName)) {
                    ToastUtils.show(mContext, "请选择签署单位")
                    return@OnClickListener
                }
                projectName = bindingView.escWoChooseProject.editText.text.toString().trim()
                if (StringUtils.isEmpty(projectName)) {
                    ToastUtils.show(mContext, "请选择选择项目")
                    return@OnClickListener
                }
            }
            val reimburseDate =
                bindingView.tvWoHappenDate.text.toString().trim()
            val metWoContentS = bindingView.metWoContent.contentText.trim()
            if (StringUtils.isEmpty(metWoContentS)) {
                ToastUtils.show(mContext, "请填写报销内容")
                return@OnClickListener
            }
            val reimburseNum =
                bindingView.etWoNumberOfDocuments.text.toString().trim()
            val et_wo_money_s = bindingView.etWoMoney.getText().toString().trim()
            if (StringUtils.isEmpty(et_wo_money_s)) {
                ToastUtils.show(mContext, "请填写报销金额")
                return@OnClickListener
            }
            val reimburseDetail = bindingView.metWoChargeDetails.contentText.trim()
            amibaReimburseProjectJson.add(
                AmibaReimburseProjectJson(
                    reimburseDate,
                    metWoContentS,
                    reimburseNum,
                    et_wo_money_s,
                    reimburseDetail
                )
            )
            for (i in 0 until bindingView.llWoDetails.getChildCount()) {
                val reimburseDates = bindingView.tvWoHappenDate.text.toString().trim()
                val reimburseContent = bindingView.metWoContent.getContentText().trim()
                if (StringUtils.isEmpty(reimburseContent)) {
                    ToastUtils.show(mContext, "请填写报销内容")
                    return@OnClickListener
                }
                val reimburseNums = bindingView.etWoNumberOfDocuments.text.toString().trim()
                val reimburseMoney = bindingView.etWoMoney.text.toString().trim()
                if (StringUtils.isEmpty(reimburseMoney)) {
                    ToastUtils.show(mContext, "请填写报销金额")
                    return@OnClickListener
                }
                val met_wo_charge_details_s_v =
                    bindingView.metWoChargeDetails.getContentText().trim()
                amibaReimburseProjectJson.add(
                    AmibaReimburseProjectJson(
                        reimburseDates,
                        reimburseContent,
                        reimburseNums,
                        reimburseMoney,
                        met_wo_charge_details_s_v
                    )
                )
            }
            val reimburseprojectjsonS = Gson().toJson(amibaReimburseProjectJson)
            val approvalUser =
                bindingView.escWoRelatedApprover.editText.getText().toString().trim()
            if (StringUtils.isEmpty(approvalUser)) {
                ToastUtils.show(mContext, "请选择关联审批人")
                return@OnClickListener
            }
            val files1: MutableList<File> = ArrayList()
            for (i in mSelectList.indices) {
                if (!mSelectList[i].getPath().startsWith("http")) {
                    files1.add(File(mSelectList[i].getPath()))
                }
            }
            addAmibaReimburse(
                orgId,
                orgName,
                customerId,
                customerName,
                amibaCustomerProjectId,
                projectName,
                amibaProjectId,
                provideProjectName,
                approvalUserId,
                approvalUser,
                2,
                "宁创",
                files1.toTypedArray(),
                reimburseprojectjsonS
            )
        })
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                111 -> bindingView.tvWoHappenDate.setText(data?.getStringExtra("date"))
                222 -> {
                    bindingView.tvWoHappenDate.setText(data?.getStringExtra("date"))
                    // 图片选择
                    mSelectList = PictureSelector.obtainMultipleResult(data)
                    mAdapter?.setSelectList(mSelectList)
                    mAdapter?.notifyDataSetChanged()
                }
                PictureConfig.CHOOSE_REQUEST -> {
                    mSelectList = PictureSelector.obtainMultipleResult(data)
                    mAdapter?.setSelectList(mSelectList)
                    mAdapter?.notifyDataSetChanged()
                }
            }
        }
    }

    override fun setData() {
        applyUserType = intent.getIntExtra("applyUserType", 0)
        orgId = SharedPreUtils.getInteger("orgId", 0)
        orgName = SharedPreUtils.getString("orgName")


        publicViewModel.getAmibaProjectListByOrgId(orgId)
            .observe(this, object : ObserverState<MutableList<AmibaProjectListBean>>() {
                override fun onDataChange(data: MutableList<AmibaProjectListBean>) {
                    val strings = arrayOfNulls<String>(data.size)
                    data.forEachIndexed { index, amountAllocatedBean ->
                        strings[index] = amountAllocatedBean.projectName
                    }
                    bindingView.escWoChoosePdProject.initAdapter(strings)
                    bindingView.escWoChoosePdProject.setOnItemClickListener { parent, view, position, id ->
                        amibaProjectId = data[position].amibaProjectId
                    }
                    super.onDataChange(data)
                }
            })

        //请求
        publicViewModel.getAmibaCustomerListByOrgId(orgId).observe(this,
            object : ObserverState<MutableList<AmeobaCustomerListBean>>() {
                override fun onDataChange(data: MutableList<AmeobaCustomerListBean>) {
                    val arrayOfStrings = arrayOfNulls<String>(data.size).apply {
                        for (index in data.indices) {
                            this[index] = data[index].customerName
                        }
                    }
                    bindingView.escWoChooseUnit.initAdapter(arrayOfStrings)
                    bindingView.escWoChooseUnit.setOnItemClickListener { _, _, position, _ ->
                        amibaCustomerProjectId = data[position].customerId
                    }
                    super.onDataChange(data)
                }
            })

        publicViewModel.getAmibaSysUserAdminByOrgId(orgId)
            .observe(this, object : ObserverState<MutableList<AmibaSysUserAdminBean>>() {
                override fun onDataChange(data: MutableList<AmibaSysUserAdminBean>) {
                    val strings = arrayOfNulls<String>(data.size)
                    data.forEachIndexed { index, amountAllocatedBean ->
                        strings[index] = amountAllocatedBean.personName
                    }
                    bindingView.escWoRelatedApprover.initAdapter(strings)
                    bindingView.escWoRelatedApprover.setOnItemClickListener { _, _, position, id ->
                        approvalUserId = data[position].userId
                    }
                    super.onDataChange(data)
                }
            })

        val manager = GridLayoutManager(mContext, 3, RecyclerView.VERTICAL, false)
        bindingView.rlvWoEvidence.layoutManager = manager
        bindingView.rlvWoEvidence.adapter = ImageSelectGridAdapter(mContext, this).also { mAdapter = it }
        mAdapter?.setSelectList(mSelectList)
        mAdapter?.setSelectMax(9)
        mAdapter?.setOnItemClickListener(object : ImageSelectGridAdapter.OnItemClickListener {
            override fun onItemClick(position: Int, v: View?) {
                PictureSelector.create(this@WipeOutAddActivity).themeStyle(R.style.XUIPictureStyle)
                    .openExternalPreview(position, mSelectList)
            }
        })
    }

    override fun onAddPicClick() {
        Utils.getPictureSelector(this)
            .selectionMedia(mSelectList)
            .maxSelectNum(9)
            .forResult(PictureConfig.CHOOSE_REQUEST)
    }

    /**
     * app端添加阿米巴付款接口
     */
    fun addAmibaReimburse(
        orgId: Int,
        orgName: String,
        customerId: Int,
        customerName: String,
        amibaCustomerProjectId: Int,
        projectName: String,
        amibaProjectId: Int,
        provideProjectName: String,
        approvalUserId: Int,
        approvalUser: String,
        sendUserId: Int,
        sendUser: String,
        imgs: Array<File>,
        amibaReimburseProjectJson: String
    ) {
        val customDialog = CustomDialog(mContext, "正在加载...")
        customDialog.show()

        val map = mutableMapOf<String, Any>().apply {
            put("amibaReimburseType", if (bindingView.rbWoP.isChecked()) 1 else 2)
            put("applyUserType", applyUserType)
            put("applyUserId", SharedPreUtils.getInteger("userId", 0))
            put("orgId", orgId)
            put("orgName", orgName)
            if (!bindingView.rbWoP.isChecked) {
                put("customerId", customerId)
                put("customerName", customerName)
                put("amibaCustomerProjectId", amibaCustomerProjectId)
                put("projectName", projectName)
            } else {
                put("amibaProjectId", amibaProjectId)
                put("provideProjectName", provideProjectName)
            }
            put("approvalUserId", approvalUserId)
            put("approvalUser", approvalUser)
            put("sendUserId", sendUserId)
            put("sendUser", sendUser)
            put("createUser", SharedPreUtils.getString("personName"))
            try {
                put("imgs", imgs)
            } catch (e: FileNotFoundException) {
                e.printStackTrace()
            }
            put("amibaReimburseProjectJson", amibaReimburseProjectJson)
        }
        viewModel.addAmibaReimburse(getRequestBody(map)).observe(this,object : ObserverState<BaseBean>(){
            override fun onDataChange(data: BaseBean) {
                customDialog.dismiss()
                finishActivity()
                super.onDataChange(data)
            }

            override fun onError(msg: String?, code: Int) {
                customDialog.dismiss()
                ToastUtils.showShort(mContext, msg)
                super.onError(msg, code)
            }
        })
    }

}